﻿using AutoMapper;
using Microsoft.AspNetCore.WebUtilities;
using System.Text.Json;
using TrackSystem.Entities.Dtos.Channel;
using TrackSystem.Entities.RequestFeatures;
using TrackSystem.UI.Server.Features;

namespace TrackSystem.UI.Server.HttpRepository.Channel
{
    public class ChannelHttpRepository : HttpRepository<ChannelDto, ChannelWithSensorsDto>,  IChannelHttpRepository
    {
        private readonly HttpClient client;
        private readonly IMapper mapper;

        public ChannelHttpRepository(HttpClient client,
            IMapper mapper) : base(client, mapper)
        {
            this.client = client;
            this.mapper = mapper;
            Name = "channel";
        }

        public async Task<IEnumerable<ChannelWithSensorsDto>?> GetAllWithSensors()
        {
            var response = await client.GetAsync("api/channel/all/sensor");
            var content = await response.Content.ReadAsStringAsync();
            var items = JsonSerializer.Deserialize<IEnumerable<ChannelWithSensorsDto>>(
                content,
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            return items;
        }

        public async Task<PagingResponse<ChannelDto>> GetChannels(RequestParameter productParameters)
        {
            var queryStringParam = new Dictionary<string, string>
            {
                ["PageNumber"] = productParameters.PageNumber.ToString(),
                ["PageSize"] = productParameters.PageSize.ToString(),
            };

            var response = await client.GetAsync(
                QueryHelpers.AddQueryString("api/channel/paged", queryStringParam));
            var content = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                throw new ApplicationException(content);
            }

            var pagingReponse = new PagingResponse<ChannelDto>
            {
                Items = JsonSerializer.Deserialize<List<ChannelDto>>(
                    content,
                    new JsonSerializerOptions { PropertyNameCaseInsensitive = true }),
            };
            if (response.Headers.TryGetValues("X-Pagination", out var a))
            {
                foreach(var item in a)
                {
                    pagingReponse.MetaData = JsonSerializer.Deserialize<PagedMetaData>(item,
                        new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
                }
            }

            return pagingReponse;
        }
    }
}
